package org.simplespringframework.mvc.render.impl;

import org.simplespringframework.mvc.RequestProcessorChain;
import org.simplespringframework.mvc.render.ResultRender;
import org.simplespringframework.mvc.type.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @BelongsProject: simpleframework
 * @BelongsPackage: org.simplespringframework.mvc.render.impl
 * @Author: xshang
 * @CreateTime: 2023-06-28  16:41
 * @Description: 页面渲染器
 * @Version: 1.0
 */
public class ViewResultRender implements ResultRender {

    public static final String VIEW_PATH = "/templates/";
    private final ModelAndView modelAndView;

    public ViewResultRender(Object mv) {

        if (mv instanceof ModelAndView) {
            // 1.如果入参类型是ModelAndView ，则直接赋值给成员变量
            this.modelAndView = (ModelAndView) mv;
        } else if (mv instanceof String) {
            // 2.如果入参类型是String，则为试图，需要包装后才赋值给成员变量
            this.modelAndView = new ModelAndView().setView((String) mv);
        } else {
            // 3.针对其他情况，则直接抛出异常
            throw new RuntimeException("传入的类型不是ModelAndView类型， 也不是String类型");
        }

    }

    /**
     * 将请求处理结果按照试图路径转发到对应的试图进行展示
     *
     * @param requestProcessorChain requestProcessorChain
     */

    @Override
    public void render(RequestProcessorChain requestProcessorChain) throws Exception {
        HttpServletRequest request = requestProcessorChain.getRequest();
        HttpServletResponse response = requestProcessorChain.getResponse();
        String path = modelAndView.getView();
        Map<String, Object> model = modelAndView.getModel();
        for (Map.Entry<String, Object> entry : model.entrySet()) {
            request.setAttribute(entry.getKey(), entry.getValue());
        }
        // JSP
        request.getRequestDispatcher(VIEW_PATH + path).forward(request, response);

    }
}
